package com.zk.babala.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.ViewGroup;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.core.view.WindowInsetsControllerCompat;

import com.zk.babala.BabalaApp;
import com.zk.babala.R;
import com.zk.babala.entity.Movie;
import com.zk.babala.entity.PlayNumInfo;
import com.zk.babala.module.EpisodeControlBar;
import com.zk.babala.util.HistoryUtil;

import java.util.List;

public class VideoActivity extends AppCompatActivity {

    private VideoView videoView;
    private List<PlayNumInfo> currLinePlayNumList;
    //视频信息
    private Movie movie;
    //播放集数
    private PlayNumInfo playNum;
    private long outKeyTime = 0;
    private String playUrl;
    private int mVideoWidth;
    private int mVideoHeight;
    private float mVideoAspectRatio = 0f;
    MediaController mediaController;
    private EpisodeControlBar episodeControlBar;


    @SuppressLint("SourceLockedOrientationActivity")
    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
        setContentView(R.layout.video_activity);
        videoView = findViewById(R.id.videoView);
        Intent intent = getIntent();
        movie = (Movie) intent.getSerializableExtra("movie");
        playNum = (PlayNumInfo) intent.getSerializableExtra("playNum");
        currLinePlayNumList = (List<PlayNumInfo>) intent.getSerializableExtra("currLinePlayNumList");
        WindowInsetsControllerCompat controller = ViewCompat.getWindowInsetsController(videoView);
        controller.hide(WindowInsetsCompat.Type.systemBars());
        mediaController = new MediaController(this, false);
        mediaController.setPrevNextListeners(nextView -> {
            playNext();
        }, preView -> {
            playPre();

        });
        videoView.setMediaController(mediaController);
        videoView.setOnPreparedListener(mp -> {
            // 计算视频的宽高比例来修改videoView的大小
            mVideoWidth = mp.getVideoWidth();
            mVideoHeight = mp.getVideoHeight();
            if (mVideoAspectRatio == 0f && mVideoWidth > 0 && mVideoHeight > 0) {
                mVideoAspectRatio = (float) mVideoWidth / mVideoHeight;
                adjustVideoSize();
            }
            videoView.start();
        });

        videoView.setOnErrorListener((mp, what, extra) -> {
            Toast.makeText(VideoActivity.this, "视频播放错误: " + playUrl, Toast.LENGTH_LONG).show();
            finish();
            return true;
        });

        videoView.setOnCompletionListener(mp -> playNext());

        // 初始化 EpisodeControlBar
        episodeControlBar = findViewById(R.id.episode_control_bar);
        episodeControlBar.setAllEpisodes(currLinePlayNumList);
        // 设置选集选择监听器
        episodeControlBar.setOnEpisodeSelectedListener(playNumInfo -> {
            playNum = playNumInfo;
            play();
        });
        play();
    }

    public void playNext() {
        if ((currLinePlayNumList.size() - 1) == playNum.getId()) {
            Toast.makeText(this, "播放完毕！", Toast.LENGTH_LONG).show();
            finish();
        } else {
            playNum = currLinePlayNumList.get(playNum.getId() + 1);
            play();
        }
    }

    public void playPre() {
        if (0 == playNum.getId()) {
            videoView.seekTo(0);
            Toast.makeText(VideoActivity.this, "正在播放: " + playNum.getTitle(), Toast.LENGTH_LONG).show();
        } else {
            playNum = currLinePlayNumList.get(playNum.getId() - 1);
            play();
        }
    }

    public void play() {
        try {
            playUrl = BabalaApp.getSourceParse().getPlayUrl(playNum.getPageUrl());
            movie.setPlayHis(playNum.getTitle());
            movie.setId(playNum.getId());
            if (currLinePlayNumList.size() > 5) {
                HistoryUtil.getHistoryInstance().addMovieHis(movie);
            }
            Uri uri = Uri.parse(playUrl);
            videoView.setVideoURI(uri);
            Toast.makeText(getBaseContext(), "正在播放: " + playNum.getTitle(), Toast.LENGTH_LONG).show();
            episodeControlBar.hide();
            episodeControlBar.setEpisodes(playNum);
        } catch (Exception e) {
            Toast.makeText(BabalaApp.getContext(), "未解析到视频播放地址 " + playNum.getPageUrl(), Toast.LENGTH_SHORT).show();
        }


    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                if (episodeControlBar.isShown()) {
                    episodeControlBar.hide();
                    return true;
                }
                if ((System.currentTimeMillis() - outKeyTime) > 1000) {
                    Toast.makeText(this, "再按一次退出播放！", Toast.LENGTH_LONG).show();
                    outKeyTime = System.currentTimeMillis();
                    return true;
                }
            }
            if (episodeControlBar.isShown()) {
                episodeControlBar.bringToFront();
                super.onKeyDown(keyCode, event);
                return false;
            }

            if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
                episodeControlBar.hide();
                mediaController.show(3000);
                focusSeekBar(mediaController);
                return true;
            }
            if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
                mediaController.hide();
                episodeControlBar.show();
                return true;
            }

        }

        return super.onKeyDown(keyCode, event);
    }

    private boolean focusSeekBar(android.view.View view) {
        if (view instanceof android.widget.SeekBar) {
            view.requestFocus();
            return true;
        }

        if (view instanceof ViewGroup) {
            ViewGroup viewGroup = (ViewGroup) view;
            for (int i = 0; i < viewGroup.getChildCount(); i++) {
                if (focusSeekBar(viewGroup.getChildAt(i))) {
                    return true;
                }
            }
        }
        return false;
    }

    // 调整视频视图尺寸
    private void adjustVideoSize() {
        if (mVideoAspectRatio <= 0) return;
        // 获取父容器可用空间
        int parentWidth = videoView.getWidth();
        int parentHeight = videoView.getHeight();
        // 计算最佳显示尺寸
        int targetWidth;
        int targetHeight;
        if (parentWidth > 0 && parentHeight > 0) {
            float parentAspect = (float) parentWidth / parentHeight;
            if (mVideoAspectRatio > parentAspect) {
                // 视频更宽 - 宽度匹配父容器
                targetWidth = parentWidth;
                targetHeight = (int) (parentWidth / mVideoAspectRatio);
            } else {
                // 视频更高 - 高度匹配父容器
                targetHeight = parentHeight;
                targetWidth = (int) (parentHeight * mVideoAspectRatio);
            }
        } else {
            // 使用视频原始尺寸作为默认值
            targetWidth = mVideoWidth;
            targetHeight = mVideoHeight;
        }
        // 设置视频视图尺寸
        ViewGroup.LayoutParams params = videoView.getLayoutParams();
        params.width = targetWidth;
        params.height = targetHeight;
    }

}
